package org.example.socket;

import cn.hutool.core.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestServer.class);

    private static final int PORT = 8800;


    public void start() throws IOException {
        ServerSocket server = new ServerSocket(PORT);
        LOGGER.info("服务端启动成功");
        while (true) {
            Socket socket = server.accept();
            SocketThread socketThread = new SocketThread(socket);
            new Thread(socketThread).start();
        }
    }

    public static void main(String[] args) {
        TestServer testServer = new TestServer();
            try {
                testServer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    class SocketThread implements Runnable {

        private Socket socket;

        SocketThread(Socket socket) {
            this.socket = socket;
        }

        private void init(String filename) {
            boolean exists = FileUtil.exist(filename);
            if (exists) {
                FileUtil.del(filename);
                LOGGER.info("清理文件 filename:{}", filename);
            } else {
                String dir = FileUtil.getParent(filename, 1);
                FileUtil.mkdir(dir);
                LOGGER.info("创建文件目录 filedir:{}", dir);
            }
        }

        @Override
        public void run() {
            DataInputStream dis = null;
            DataOutputStream dos = null;
            String fileName = null;
            long fileSize = 0;
            try {
                dis = new DataInputStream(socket.getInputStream());
                fileName = dis.readUTF();
                fileSize = dis.readLong();
                init(fileName);
                dos = new DataOutputStream(new FileOutputStream(fileName));
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalRead = 0;

                while ((bytesRead = dis.read(buffer)) != -1) {
                    dos.write(buffer, 0, bytesRead);
                    totalRead += bytesRead;
                    if (totalRead >= fileSize) break;
                }
                LOGGER.info("文件接受成功。fineName={},filesize={}", fileName, fileSize);
            } catch (Exception e) {
                LOGGER.error("socket 接收文件失败！fineName={},filesize={},err:{}", fileName, fileSize, e.getMessage(), e);
            } finally {
                if (dis != null) {
                    try {
                        dis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        dis = null;
                    }
                }
                if (dos != null) {
                    try {
                        dos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        dos = null;
                    }
                }
            }

        }
    }

}
